package com.ydl.shopping.serializer;

import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;
import com.ydl.shopping.annotation.DataMask;
import com.ydl.shopping.core.enums.DataMaskType;

import java.io.IOException;

public class DataMaskSerializer extends JsonSerializer<String> implements ContextualSerializer {
    /**
     * 脱敏类型，默认为DEFAULT
     */
    private DataMaskType type;
    /**
     * 脱敏起始位置
     */
    private int startInclude;
    /**
     * 脱敏结束位置
     */
    private int endExclude;

    public DataMaskSerializer() {
        this.type = DataMaskType.DEFAULT;
    }

    public DataMaskSerializer(DataMaskType type) {
        this.type = type;
    }

    @Override
    public void serialize(String value, JsonGenerator gen, SerializerProvider serializerProvider) throws IOException {
        switch (type) {
            // 这里是对字符串的startInclude到endExclude字段进行隐藏处理，如果想要实现两端保留，可以考虑使用StrUtil的replace方法
            case CUSTOM_RULE -> gen.writeString(StrUtil.hide(value, startInclude, endExclude));
            case PHONE -> gen.writeString(DesensitizedUtil.mobilePhone(value));
            case EMAIL -> gen.writeString(DesensitizedUtil.email(value));
            case ID_CARD -> gen.writeString(DesensitizedUtil.idCardNum(value, 1, 2));
            case BANK_CARD -> gen.writeString(DesensitizedUtil.bankCard(value));
            case ADDRESS -> gen.writeString(DesensitizedUtil.address(value, 8));
            case CHINESE_NAME -> gen.writeString(DesensitizedUtil.chineseName(value));
            case PASSWORD -> gen.writeString(DesensitizedUtil.password(value));
            default -> gen.writeString(value);
        }
    }


    @Override
    public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty) throws JsonMappingException {
        if (beanProperty != null) {
            DataMask annotation = beanProperty.getAnnotation(DataMask.class);
            if (annotation != null) {
                this.type = annotation.type();
                if (annotation.type() == DataMaskType.CUSTOM_RULE) {
                    this.startInclude = annotation.startInclude();
                    this.endExclude = annotation.endExclude();
                }
            }
        }
        return this;
    }
}
